<include file='Index/header' />
<div class="row">
	<br>
	<div class="col-sm-12">
		<div class="col-sm-2" style="padding-left:15px;padding-top:5px">
			<label for="order_serial_id" class="control-label">订单号：</label>
		</div>
		<div class="col-sm-3">
			<input id="order_serial_id_search" class="form-control"></input>
		</div>
		<div class="col-sm-3" style="padding-left:90px;padding-top:5px">
			<label for="status" class="control-label">订单状态：</label>
		</div>
		<div class="col-sm-3">
      <select class="form-control" id="status_search" name="status_search">
	      <option value="" selected="selected">请选择</option>
				<option value="0">已发货</option>
				<option value="1">已付款</option>
				<option value="2">已完成</option>
				<option value="3">待退货</option>
				<option value="4">已退货</option>
			</select>
    </div>
	</div>
	<div class="col-sm-12">
		<br>
	<table id="order_list_table" class="table table-hover table-bordered table-striped table-striped">
		<thead>
			<tr>
				<td>订单号</td>
				<td>下单时间</td>
				<td>收货人</td>
				<td>总金额</td>
				<td>应付金额</td>
				<td>status</td>
				<td>订单状态</td>
				<td>操作</td>
			</tr>
		</thead>
		<tbody>

		</tbody>
	</table>
</div>
</div>

<include file='Index/footer' />
<include file='Order/order-detail' />
<script>
$(document).ready(function() {
		loadTable();
});
var table;
function loadTable(){
	table = $('#order_list_table').DataTable({
		"bProcessing": true,
		"bDestroy": true,
		"sPaginationType" : "input",
		"order": [[ 1, "desc" ]],
		"oLanguage" : {
              "sLengthMenu": "每页显示 _MENU_ 条记录",
              "sZeroRecords": "抱歉， 没有找到",
              "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
              "sInfoEmpty": "没有数据",
              "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
              "sZeroRecords": "没有检索到数据",
               "sSearch": "搜索: &nbsp",
              "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
              }
          }, 
		"ajax":'{:U("Admin/Order/getOrder/")}',
		"columns": [
					{ "data": 'order_serial_id' },
					{ "data": 'createtime' },
	        { "data": 'user_id' },
	        { "data": 'price' },
	        { "data": 'realprice' },
	        { "data": 'status' },
	        { "data": 'status' },
	        { "data": 'btn' }
    ],
    "columnDefs": [
    {
			"targets": 1,
			"render": function (data, type, row, table) {
        return row.createtime;
      }
    },
    {
			"targets": 2,
			"render": function (data, type, row, table) {
        return row.receivename + '<br>' + row.phone + '<br>' + row.address;
      }
    },
    {
			"targets": [3, 4],
			"render": function (data, type, row, table) {
        return (parseFloat(data) + parseFloat(row.sendprice)).toFixed(2) + '元';
      }
    },
    {
			"targets": 5,
			"visible":false
    },
    {
			"targets": -2,
			"render": function (data, type, row, table) {
				var status;
				switch(data){
					case '0':
						status = '已发货';
						break;
					case '1':
						status = '已付款';
						break;
					case '2':
						status = '已完成';
						break;
					case '3':
						status = '待退货';
						break;
					case '4':
						status = '已退货';
						break;
				}
        return status;
      }
    },
    {
    	"targets": -1,
    	"data": null,
    	"render": function (data, type, row, table) {
        return '<button class="btn btn-info" onclick="view(\''+row.order_id+'\')">查看</button>';
      },
    }]
	});

	$("#order_serial_id_search").keyup(function(){
		table.column(0).search(this.value).draw();
  });

	$("#status_search").on( 'change', function () {
 		table.column(5).search(this.value).draw();
  });
}

function view(order_id){
	$.ajax({
			url: '{:U("Admin/Order/getOrder/")}',
			type: 'post',
			dataType: 'json',
			data:{
				"order_id":order_id
			}
		})
		.success(function(data){
			$('#order_serial_id').html(data.order_serial_id);
			switch(data.status){
				case '0':
					$('#status').html('已发货');
					break;
				case '1':
					$('#status').html('已付款');
					break;
				case '2':
					$('#status').html('已完成');
					break;
				case '3':
					$('#status').html('待退货');
					break;
				case '4':
					$('#status').html('已退货');
					break;
			}
			
			$('#createtime1').html(data.createtime);
			$('#createtime2').html(data.createtime);
			$('#username').html(data.user.name);
			$('#price').html((parseFloat(data.price)+parseFloat(data.sendprice)).toFixed(2) + "元");
			$('#realprice').html((parseFloat(data.realprice)+parseFloat(data.sendprice)).toFixed(2) + "元");
			$('#receivename').html(data.receivename);
			$('#address').html(data.address);
			$('#phone').html(data.phone);
			$('#note').html(transNull(data.note));
			
			var sendTime = 39;
			var products = data.products;
			var a_html = '', b_html = '';
			var a_amount = 0, b_amount = 0; 
			var a_realprice = 0, b_realprice = 0;
			var hasA = false, hasB = false;//判断是否有ab仓库的货物
			for (var i = 0; i < products.length; i++) {
				if(products[i].b_repository_id == null || products[i].b_repository_id == '0'){
					//如果商品sendtype!=0，选择新的sentime
					if(products[i].sendtype != '0'){
						if(products[i].sendtype == '1'){
							sendTime = Math.max(sendTime, 49);
						}else if(products[i].sendtype == '2'){
							sendTime = Math.max(sendTime, 59);
						}
					}
					hasA = true;
					a_html += '<tr>'+
                			'<td>'+transNull(products[i].name)+'</td>'+
                			'<td>'+transNull(products[i].barcode)+'</td>'+
                			'<td>'+transNull(products[i].kj_price)+'</td>'+
                			'<td>'+transNull(products[i].num)+'</td>'+
                			'<td>'+transNull(products[i].origin_place)+'</td>'+
                			'<td>'+transNull(products[i].default_amount)+'</td>'+
                			'<td>'+(products[i].kj_price*products[i].num).toFixed(2)+'</td>';
          a_amount += products[i].kj_price*products[i].num;
          a_realprice += products[i].realprice*products[i].num;

          var btntext, status;
          if(products[i].status == '0'){
						btntext = '已退货';
						status = '1';
						 a_html += '<td id="product'+products[i].order_product_id+'"><button class="btn btn-primary" onclick="returnModal(\''+order_id+'\',\''+products[i].order_product_id+'\',\''+status+'\',\''+products[i].num+'\')"">'+btntext+'</button></td></tr>';
          }else {
						btntext = '无需操作';
						 a_html += '<td></td></tr>';
          }
         
                			
				}else if(products[i].a_repository_id == null || products[i].a_repository_id == '0'){
					sendTime = 1*24*60;
					hasB = true;
					b_html += '<tr>'+
                			'<td>'+transNull(products[i].name)+'</td>'+
                			'<td>'+transNull(products[i].barcode)+'</td>'+
                			'<td>'+transNull(products[i].kj_price)+'</td>'+
                			'<td>'+transNull(products[i].num)+'</td>'+
                			'<td>'+transNull(products[i].origin_place)+'</td>'+
                			'<td>'+transNull(products[i].default_amount)+'</td>'+
                			'<td>'+(products[i].kj_price*products[i].num).toFixed(2)+'</td>';
          b_amount += products[i].kj_price*products[i].num;
          b_realprice += products[i].realprice*products[i].num;

          var btntext, status;
          if(products[i].status == '0'){
						btntext = '已退货';
						status = '1';
						 b_html += '<td id="product'+products[i].order_product_id+'"><button class="btn btn-primary" onclick="returnModal(\''+order_id+'\',\''+products[i].order_product_id+'\',\''+status+'\',\''+products[i].num+'\')"">'+btntext+'</button></td></tr>';
          }else {
						btntext = '无需操作';
						 b_html += '<td></td></tr>';
          }
				}
			}

			//收货时间的计算
			if(data.type == '0'){
				$('#receivetime').html(addDate(data.createtime, sendTime));
			}else{
				$('#receivetime').html(addDate(data.createtime, 1*24*60));
			}
			a_html += '<tr><td></td><td></td><td></td><td></td><td></td><td>合计</td><td>'+a_amount.toFixed(2)+'</td><td></td></tr>';
			b_html += '<tr><td></td><td></td><td></td><td></td><td></td><td>合计</td><td>'+b_amount.toFixed(2)+'</td><td></td></tr>';
			$('#a_product').html(a_html);
			$('#b_product').html(b_html);

			var a_price = "￥"+a_amount.toFixed(2)+" - 折扣：￥"+(a_amount-a_realprice).toFixed(2);
			var a_order_realprice = "￥"+a_realprice.toFixed(2);
			if(hasA){
				a_price =  a_price+" +  配送费：￥"+parseFloat(data.sendprice).toFixed(2);
				a_order_realprice = "￥"+(parseFloat(a_realprice)+parseFloat(data.sendprice)).toFixed(2);
			}
			$('#a_price').html(a_price);
			$('#a_realprice').html(a_order_realprice);

			var b_price = "￥"+b_amount.toFixed(2)+" - 折扣：￥"+(b_amount-b_realprice).toFixed(2);
			var b_order_realprice = "￥"+(b_realprice).toFixed(2);
			if(hasB && !hasA){
				b_price =  b_price+" +  配送费：￥"+parseFloat(data.sendprice).toFixed(2);
				b_order_realprice = "￥"+(parseFloat(b_realprice)+parseFloat(data.sendprice)).toFixed(2);
			}
			$('#b_price').html(b_price);
			$('#b_realprice').html(b_order_realprice);

			var btntext;
			switch(data.status){
				case '0':
					$('#log_btn').html('<button class="btn btn-primary" onclick="modOrderStatus(\''+data.order_id+'\', \'1\')">已付款</button>');
					break;
				// case '3':
				// 	$('#log_btn').html('<button class="btn btn-primary" onclick="modOrderStatus(\''+data.order_id+'\', \'4\')">已退货</button>');
				// 	break;
				default:
					$('#log_btn').html('<button class="btn btn-primary" >无需操作</button>');
					break;
			}

			var log = data.log;
			var admin = data.admin;
			var log_html = '';
			for (var i = 0; i < log.length; i++) {

				var orderstatus;
				switch(log[i].status){
					case '1':
						orderstatus = '已付款';
						break;
					case '4':
						orderstatus = '已退货';
						break;
					default:
						break;

				}
				log_html += '<tr>'+
					'<td>'+admin[i].name+'</td>'+
					'<td>'+log[i].createtime+'</td>'+
					'<td>'+orderstatus+'</td>'+
					'<td>'+transNull(log[i].note)+'</td>'+
					'</tr>';
			}
			
			$('#log_table').html(log_html);
			$('#order_detail_modal').modal({
				backdrop : "static"
			});
	});
}

function modOrderStatus(order_id, status){
	$.ajax({
		url: '{:U("Admin/Order/modOrderStatus/")}',
		type: 'post',
		dataType: 'json',
		data:{
			"order_id":order_id,
			"status":status,
			"note":$('#note').val()
		}
	})
	.success(function(data){
		$('#note').val('');
		view(order_id);
	});
}

var order_id, order_product_id, status, buy_num;
function returnModal(order_id, order_product_id, status, buy_num){
	$('#order_detail_modal').modal('hide');
	$('#return_modal').modal({
		backdrop : "static"
	});
	window.order_id = order_id;
	window.order_product_id = order_product_id;
	window.status = status;
	window.buy_num = buy_num;
}

function modProductStatus(){
	if($('#return_num').val() > buy_num){
		alert("退货数量大于购买数量！");
		return;
	}
	$.ajax({
		url: '{:U("Admin/Order/modProductStatus/")}',
		type: 'post',
		dataType: 'json',
		data:{
			"order_id":order_id,
			"order_product_id":order_product_id,
			"status":status,
			"return_num":$('#return_num').val()
		}
	})
	.success(function(data){
		$('#return_modal').modal('hide');
		$('#product'+order_product_id).html("");
		$('#note').val('');
		view(order_id);
	});
}
</script>
